import { useThrottle } from "@/hooks";
import { vectorToTuple } from "@/utils/model";
import { TransformControls } from "@react-three/drei";
import { useControls } from "leva";
import { useEffect, useMemo, useState } from "react";
import { Object3D, Vector3Tuple } from "three";
/**
 * 牵引调试器
 *
 * 用于在调试面板上显示模型的牵引调试信息。
 */
export default function Tractor({
  name = "牵引器",
  object,
  metaData,
  track,
}: {
  name?: string;
  metaData?: Partial<ObjectProps>;
  object: Object3D;
  track?: () => void; // 模型被牵引时调用
}) {
  const data = useMemo(
    () => ({
      position: vectorToTuple(object.position),
      rotation: vectorToTuple(object.rotation),
      scale: vectorToTuple(object.scale),
      ...metaData,
    }),
    [object, metaData]
  );
  const [isDragging, setIsDragging] = useState(false); // 状态变量
  const [{ 模式, 撤销, 位置, 旋转, 缩放 }, set] = useControls(name, () => ({
    所选模型: "未选择",
    模式: {
      value: "移动",
      options: ["移动", "旋转", "缩放"],
    },
    位置: data.position,
    旋转: data.rotation,
    缩放: data.scale,
    撤销: false,
  }));

  useEffect(() => {
    updatePanel();
  }, [object]);

  useEffect(() => {
    if (!撤销) return;
    resetObj();
    track && track();
  }, [撤销]);

  useEffect(() => {
    if (isDragging) return;
    object.position.set(...位置);
    object.rotation.set(...旋转);
    if (Array.isArray(缩放)) {
      object.scale.set(...缩放);
    } else {
      object.scale.setScalar(缩放);
    }

    track && track();
  }, [位置, 旋转, 缩放]);

  // 重置模型空间矩阵信息
  function resetObj() {
    const { position, rotation, scale } = data;
    switch (模式) {
      case "移动":
        object.position.set(...position);
        set({ 位置: position });
        break;
      case "旋转":
        object.rotation.set(...rotation);
        set({ 旋转: rotation });
        break;
      case "缩放":
        if (Array.isArray(scale)) {
          object.scale.set(...scale);
        } else {
          object.scale.setScalar(scale);
        }
        set({ 缩放: scale });
        break;
      default:
        console.error("无法重置未知模式！");
        break;
    }
    set({
      撤销: false,
    });
  }

  // 更新面板信息
  function updatePanel() {
    set({
      所选模型: object.name || "未命名",
      位置: vectorToTuple(object.position),
      旋转: vectorToTuple(object.rotation),
      缩放: vectorToTuple(object.scale),
    });
  }
  const updateThrottle = useThrottle(updatePanel, 50);

  return (
    <group dispose={null}>
      <TransformControls
        mode={MODE[模式]}
        object={object}
        onObjectChange={() => {
          track && track();
          updateThrottle();
        }}
        onMouseDown={() => setIsDragging(true)} // 开始拖拽
        onMouseUp={() => setIsDragging(false)} // 结束拖拽
      />
    </group>
  );
}

const MODE: TransformModes = {
  移动: "translate",
  旋转: "rotate",
  缩放: "scale",
};
type TransformModes = {
  [key: string]: "translate" | "rotate" | "scale";
};
type ObjectProps = {
  position: Vector3Tuple;
  rotation: Vector3Tuple;
  scale: number;
};
